package com.zkthink.ceres.tenant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zkthink.base.R;
import com.zkthink.base.request.PageParams;
import com.zkthink.ceres.tenant.dto.*;
import com.zkthink.ceres.tenant.entity.Tenant;
import com.zkthink.ceres.tenant.entity.TenantApply;
import com.zkthink.ceres.tenant.enums.TenantAuditStateEnum;
import com.zkthink.ceres.tenant.service.TenantApplyService;

import java.time.LocalDateTime;
import java.util.Objects;

import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.exception.BizException;
import com.zkthink.log.annotation.SysLog;
import com.zkthink.security.annotation.PreAuth;
import com.zkthink.utils.BeanPlusUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


/**
 * <p>
 * 前端控制器
 * 商家入驻
 * </p>
 *
 * @author vivi.huang
 * @date 2020-06-28
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/tenantApply")
@Api(value = "TenantApply", tags = "商家入驻")
@AllArgsConstructor
//@PreAuth(replace = "tenantApply:")
public class TenantApplyController  {

    private TenantApplyService tenantApplyService;

    /**
     * 查询
     * @param id
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataType = "long", paramType = "query"),})
    @ApiOperation(value = "查询商家入驻信息", notes = "查询商家入驻信息")
    @GetMapping("/{id}")
    @SysLog("'查询商家入驻:' + #id")
    public R<TenantApply> getTenantApply(@PathVariable Long id) {
        return tenantApplyService.getTenantApply(id);
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键", dataType = "long", paramType = "query"),})
    @ApiOperation(value = "商家入驻页面查询入驻信息", notes = "商家入驻页面查询入驻信息")
    @GetMapping("/applyPage/{id}")
    @SysLog("'查询商家入驻:' + #id")
    public R<TenantApply> getTenantApplyOfApplyPage(@PathVariable Long id) {
        return tenantApplyService.getTenantApply(id);
    }

    /**
     * 新增
     * @param model
     * @return
     */
    @ApiOperation(value = "商家申请", notes = "商家申请")
    @PostMapping("/apply")
    @SysLog("'申请商家入驻'")
    public R<TenantApply> save(@RequestBody TenantApplySaveDTO model) {
        model.setApplyTime(LocalDateTime.now());
        model.setAuditState(TenantAuditStateEnum.WAIT_PROCESS.getCode());
        TenantApply tenantApply = BeanPlusUtil.toBean(model, TenantApply.class);

        TenantApplyAuditDTO tenantApplyAuditDTO = this.tenantApplyService.getTenantApplyByMobile(model.getHeadMobile());

        //第一次申请
        if (Objects.isNull(tenantApplyAuditDTO)) {

            //检查商家名称重复
            checkMerchantName(model);

            this.tenantApplyService.saveTenantApply(tenantApply);

        //第二次申请 但上一次申请状态为reject
        } else {
            if (TenantAuditStateEnum.REJECTED.getCode() == tenantApplyAuditDTO.getAuditState().intValue()) {
                this.tenantApplyService.removeById(tenantApply.getId());
                log.info("商家入驻清除信息成功");
                this.tenantApplyService.saveTenantApply(tenantApply);
            } else {
                //检查电话号码重复
                checkMobile(model, tenantApplyAuditDTO);
            }
        }

        log.info("商家入驻信息成功");
        return R.success(tenantApply);
    }

    private void checkMobile(@RequestBody TenantApplySaveDTO model, TenantApplyAuditDTO tenantApplyAuditDTO) {
        if (tenantApplyAuditDTO != null) {
            throw new BizException("负责人号码不能重复申请");
        }
    }

    private void checkMerchantName(@RequestBody TenantApplySaveDTO model) {
        if (StringUtils.isNotBlank(model.getMerchantName())) {

            int count = this.tenantApplyService.count(Wraps.<TenantApply>lbQ().eq(TenantApply::getMerchantName, model.getMerchantName()));
            if (count > 0) {
                throw new BizException("商家名称不能重复申请");
            }

        } else if (StringUtils.isNotBlank(model.getStoreName())) {
            int count = this.tenantApplyService.count(Wraps.<TenantApply>lbQ().eq(TenantApply::getStoreName, model.getStoreName()));
            if (count > 0) {
                throw new BizException("店铺名称不能重复申请");
            }
        }

    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "平台审核商家入驻列表查询")
    @PostMapping(value = "/page")
    @SysLog(value = "'分页列表查询:第' + #params?.current + '页, 显示' + #params?.size + '行'", response = false)
    @PreAuth("hasPermit('{}view')")
    public R<IPage<TenantApply>> findTenantApplyPage(@RequestBody @Validated PageParams<TenantApplyPageDTO> params) {
        return tenantApplyService.findTenantApplyPage(params);
    }

    /**
     * 审核
     * @return
     */
    @ApiOperation(value = "审核商家入驻", notes = "审核商家入驻")
    @PostMapping("/audit")
    @SysLog("'审核商家入驻'")
    public R<Boolean> audit(@RequestBody TenantApplyAuditDTO tenantApplyAuditDTO) {
        return this.tenantApplyService.audit(tenantApplyAuditDTO);
    }

    /**
     * 检验是否已提交商家入驻申请
     *
     */
    @ApiOperation(value = "检验商家入驻申请")
    @PostMapping("/check")
    @SysLog(value = "检验商家入驻申请", request = false)
    public R<TenantApplyAuditDTO> checkTenantApplyResult(@RequestBody @Validated TenantApplyCheckDTO tenantApplyCheckDTO) {
        return this.tenantApplyService.checkTenantApplyResult(tenantApplyCheckDTO);
    }

    /**
     * 删除商家入驻申请
     *
     */
    @ApiOperation(value = "删除商家入驻申请")
    @PostMapping("/remove")
    @SysLog(value = "删除商家入驻申请", request = false)
    public R<Boolean> removeTenantApply(@RequestBody @Validated TenantApplyUpdateDTO tenantApplyUpdateDTO) {
        return this.tenantApplyService.removeTenantApply(tenantApplyUpdateDTO);
    }


}
